#!/usr/bin/env python
# coding=utf8

import json

from app.common.factory import ConnectorFactory as CF
from app.common.exception import ServiceError
from app.model.user import User

SubmailConnector = CF.get_instance("submail")

submail_secret_key = "APTX4869"

submail_list = {
    "DAS_AUTH_SUBMAIL" : {
        "appid" : 13016,
        "project" : "zPGgt1",
        "signature" : "dea7ae880435f092948d2c84defc3e4a"
    }
}

class ExtService():
    @staticmethod
    def send_subemail(params):
        """
            params内容
            secret_key:string 安全码
            submail_type:string 短信类别
            to:string 收信人电话
            var:string json变量列表
            login:string 使用通行证
            password:string 通行证密码
        """
        secret_key = params.get("secret_key", None)
        if secret_key != submail_secret_key:
            raise ServiceError(message = "安全认证失败")

        to = params.get("to", None)
        if not to:
            raise ServiceError(message = "未指定收信人")

        submail_type = params.get("submail_type")
        if not submail_list.has_key(submail_type):
            raise ServiceError(message = "未识别的短信类别")
        appid = submail_list[submail_type].get("appid")
        project = submail_list[submail_type].get("project")
        signature = submail_list[submail_type].get("signature")

        login = params.get("login", None)
        password = params.get("password", None)
        user = User.get_user(login, password)
        if not user:
            raise ServiceError(message = "用户认证失败")
        uid = user.id

        var = params.get("var", None)
        var_json = json.dumps(var)
        res = SubmailConnector.send_subemail(appid, to, project, signature, var_json)
        return res
